package com.zyzd.baseretrofit.net;

import com.google.gson.JsonSyntaxException;
import com.zyzd.baseretrofit.exception.ApiException;
import com.zyzd.baseretrofit.utils.api.ErrorCodeUtil;
import com.zyzd.commontools.log.TLog;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by LZY on 2017/6/26.
 */

public abstract class ApiCallback<M> extends Subscriber<M> {

    public abstract void onSuccess(M model);

    public abstract void onFailure(String msg, int errorCode);

    public abstract void onFinish();

    @Override
    public void onError(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            String msg = httpException.getMessage();
            TLog.d("code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg, ErrorCodeUtil.ERROR_NET);
        } else if (e instanceof ApiException) {
            ApiException apiException = (ApiException) e;
            onFailure(e.getMessage(), apiException.getErrorCode());
        } else if (e instanceof JsonSyntaxException) {
            onFailure("解析数据异常", ErrorCodeUtil.ERROR_JSON_SYNTAX);
        } else {
            onFailure(e.getMessage(), ErrorCodeUtil.ERROR_UNKNOW);
        }
        onFinish();
    }

    @Override
    public void onNext(M model) {
        onSuccess(model);
    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
